#!/usr/bin/env python

import os
import sys
import logging.config

import ConfigParser

class App(object):
    '''App class

    @author Julot <andy.julot@gmail.com>
    @since Sunday, January 15, 2012. 05:05 PM'''
    
    _pid = None
    _homeDir = None
    
    @property
    def homeDir(self):
        if not self._homeDir:
            self._homeDir = os.path.realpath(os.path.dirname(sys.argv[0]))
        return self._homeDir
    
    @property
    def logDir(self):
        return os.path.realpath(os.path.join(self.homeDir, 'logs'))
    
    @property
    def isRunning(self, name):
        if sys.platform.find('nix') >= 0:
            import fcntl
            path = os.path.join(self.logDir, '%s.pid' % name)
            self._pid = open(path, 'w')
            try:
                fcntl.flock(self._pid, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return False
            except:
                return True
        else:
            return False

    def initConfig(self, name, data):
        path = os.path.join(self.homeDir, '%s.conf' % name)
        if not os.path.lexists(path):
            config = ConfigParser.RawConfigParser()
            for section in data:
                config.add_section(section)
                for key in data[section]:
                    config.set(section, key, data[section][key])
            with open(path, 'wb') as configFile: config.write(configFile)
    
    def initLogging(self, name):
        if not os.path.lexists(self.logDir): os.mkdir(self.logDir)
        path = os.path.join(self.homeDir, '%s.logging.conf' % name)
        if not os.path.lexists(path):
            config = ConfigParser.RawConfigParser()
    
            config.add_section('loggers')
            config.set('loggers', 'keys', 'root')
    
            config.add_section('logger_root')
            config.set('logger_root', 'handlers', 'debug,warning')
            config.set('logger_root', 'level', 'NOTSET')
    
            config.add_section('formatters')
            config.set('formatters', 'keys', 'simple,complex')
    
            config.add_section('formatter_simple')
            s = '[%(asctime)s] [%(levelname)s] %(message)s'
            config.set('formatter_simple', 'format', s)
    
            config.add_section('formatter_complex')
            s = '[%(asctime)s] [%(levelname)s] [%(module)s : '
            s += '%(lineno)d] %(message)s'
            config.set('formatter_complex', 'format', s)
    
            config.add_section('handlers')
            config.set('handlers', 'keys', 'debug,warning')
    
            config.add_section('handler_debug')
            config.set('handler_debug', 'class', 'handlers.RotatingFileHandler')
            config.set('handler_debug', 'maxBytes', '1024')
            config.set('handler_debug', 'backupCount', '30')
            config.set('handler_debug', 'formatter', 'complex')
            config.set('handler_debug', 'level', 'DEBUG')
            s = "(os.path.join(os.path.dirname(sys.argv[0]), 'logs', "
            s += "'%s.debug.log'),)"
            config.set('handler_debug', 'args', s % name)
    
            config.add_section('handler_warning')
            config.set('handler_warning', 'class',
                       'handlers.RotatingFileHandler')
            config.set('handler_warning', 'maxBytes', '1024')
            config.set('handler_warning', 'backupCount', '30')
            config.set('handler_warning', 'formatter', 'simple')
            config.set('handler_warning', 'level', 'WARNING')
            s = "(os.path.join(os.path.dirname(sys.argv[0]), 'logs', "
            s += "'%s.warning.log'),)"
            config.set('handler_warning', 'args', s % name)
    
            with open(path, 'wb') as configFile: config.write(configFile)
            
        logging.config.fileConfig(path)
    
    